package com.byyy.ccts.modules.ysjl.api.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializeFilter;
import com.byyy.ccts.core.base.ILogBase;
import com.byyy.ccts.core.model.AjaxJson;
import com.byyy.ccts.core.model.PageJson;
import com.byyy.ccts.core.query.data.Condition;
import com.byyy.ccts.core.query.data.PropertyPreFilterable;
import com.byyy.ccts.core.query.data.Queryable;
import com.byyy.ccts.core.query.utils.QueryableConvertUtils;
import com.byyy.ccts.core.query.wrapper.EntityWrapper;
import com.byyy.ccts.core.utils.StringUtils;
import com.byyy.ccts.modules.sys.entity.Dict;
import com.byyy.ccts.modules.ysjl.YsjlGlobal;
import com.byyy.ccts.modules.ysjl.entity.YsjlUser;
import com.byyy.ccts.modules.ysjl.enums.*;
import com.byyy.ccts.modules.ysjl.reqvo.AdminLoginReqVo;
import com.byyy.ccts.modules.ysjl.reqvo.AuthReqVo;
import com.byyy.ccts.modules.ysjl.service.IYsjlActivityService;
import com.byyy.ccts.modules.ysjl.service.IYsjlUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.sql.Timestamp;
import java.util.*;

/**
 * @author lyb
 * @date 2022-06-22 13:33
 * @description XX
 */
@Controller
@RequestMapping("/api/ysjl/user")
public class YsjlUserController implements ILogBase {

    @Autowired
    private IYsjlUserService ysjlUserService;

    @Autowired
    private IYsjlActivityService ysjlActivityService;

    /**
     * 查询参与活动名单详情
     */
    @RequestMapping(value = "/pageList", method = { RequestMethod.GET, RequestMethod.POST })
    @ResponseBody
    public void pageList(Queryable queryable, PropertyPreFilterable propertyPreFilterable, HttpServletRequest request,
                             HttpServletResponse response) {
        EntityWrapper<YsjlUser> entityWrapper = new EntityWrapper<YsjlUser>(YsjlUser.class);
        Condition condition = queryable.getCondition();
        if (condition != null ) {
            Condition.Filter nameFilter = queryable.getCondition().getFilterFor("name");
            if (nameFilter != null && StringUtils.isNotEmpty((String) nameFilter.getValue())) {
                nameFilter.setValue(YsjlGlobal.encodeName((String) nameFilter.getValue()));
            }
        }
        // 预处理
        QueryableConvertUtils.convertQueryValueToEntityValue(queryable, YsjlUser.class);
        SerializeFilter filter = propertyPreFilterable.constructFilter(YsjlUser.class);
        PageJson<YsjlUser> pagejson = new PageJson<YsjlUser>(this.ysjlUserService.pageUserList(queryable, entityWrapper));
        String content = JSON.toJSONString(pagejson, filter);
        StringUtils.printJson(response, content);
    }

    /**
     * 获取Ooenid，然后获取用户
     */
    @RequestMapping(value = "/wxAuth", method = {RequestMethod.GET, RequestMethod.POST })
    @ResponseBody
    public AjaxJson wxAuth(@RequestBody AuthReqVo vo) {
        AjaxJson json = new AjaxJson();
        YsjlUser ysjlUser = this.ysjlUserService.wxAuth(vo.getCode());
        json.setData(ysjlUser);
        return json;
    }

    /**
     *
     * @title: ajaxUpload
     * @description: 文件上传
     * @return
     * @return: AjaxUploadResponse
     */
    @RequestMapping(value = "uploadPic", method = RequestMethod.POST)
    @ResponseBody
    public AjaxJson uploadPic(HttpServletRequest request, MultipartFile file) {
        AjaxJson ajaxJson = new AjaxJson();
        String picUrl = this.ysjlUserService.uploadPic(request, file);
        ajaxJson.setData(picUrl);
        return ajaxJson;
    }

    /**
     * 注册
     */
    @RequestMapping(value = "/register", method = {RequestMethod.POST })
    @ResponseBody
    public AjaxJson register(HttpServletRequest request, @RequestBody YsjlUser ysjlUser) {
        AjaxJson json = new AjaxJson();
        YsjlUser user = this.ysjlUserService.register(ysjlUser);
        json.setData(user);
        return json;
    }

    /**
     * 管理员登录
     */
    @RequestMapping(value = "/adminLogin", method = {RequestMethod.POST })
    @ResponseBody
    public AjaxJson adminLogin(@RequestBody AdminLoginReqVo loginVo) {
        AjaxJson json = new AjaxJson();
        YsjlUser user = this.ysjlUserService.queryByName(loginVo.getName());
        user.setLoginTime(new Timestamp(System.currentTimeMillis()));
        this.ysjlUserService.updateById(user);
        if (user == null || !"admin@ysjl2022".equals(loginVo.getPwd())) {
            json.fail("管理员登录失败！");
            return json;
        }
        json.setData(user);
        return json;
    }

    /**
     * 后台管理首页
     */
    @RequestMapping(value = "/adminHome", method = {RequestMethod.POST })
    @ResponseBody
    public AjaxJson adminHome() {
        AjaxJson json = new AjaxJson();
        int userCnt = this.ysjlUserService.selectCount(null);
        int activityCnt = this.ysjlActivityService.selectCount(null);
        List<Map<String, Object>> retList = new ArrayList<>();
        Map<String, Object> userCntMap = new HashMap<>();
        userCntMap.put("title", "用户数");
        userCntMap.put("cnt", userCnt);
        retList.add(userCntMap);
        userCntMap = new HashMap<>();
        userCntMap.put("title", "活动数");
        userCntMap.put("cnt", activityCnt);
        retList.add(userCntMap);
        json.setData(retList);
        return json;
    }

    /**
     * 查询用户信息
     */
    @RequestMapping(value = "/userInfo", method = {RequestMethod.POST })
    @ResponseBody
    public AjaxJson userInfo(@RequestBody YsjlUser user) {
        AjaxJson json = new AjaxJson();
        user = this.ysjlUserService.userInfo(user.getId());
        json.setData(user);
        return json;
    }

    /**
     * 后台修改会员状态
     */
    @RequestMapping(value = "/status", method = { RequestMethod.GET, RequestMethod.POST })
    @ResponseBody
    public AjaxJson status(@RequestBody YsjlUser ysjlUser) {
        AjaxJson json = new AjaxJson();
        YsjlUser user = this.ysjlUserService.selectById(ysjlUser.getId());
        user.setStatus(ysjlUser.getStatus());
        this.ysjlUserService.updateById(user);
        return json;
    }

    /**
     * 后台修改会员信息
     */
    @RequestMapping(value = "/submit", method = { RequestMethod.GET, RequestMethod.POST })
    @ResponseBody
    public AjaxJson submit(@RequestBody YsjlUser ysjlUser) {
        AjaxJson json = new AjaxJson();
        String ret = this.ysjlUserService.submit(ysjlUser);
        if (StringUtils.isNotEmpty(ret)) {
            json.fail(ret);
        }
        return json;
    }

    /**
     * 前台获取数据字典值
     */
    @RequestMapping(value = "/getDict", method = {RequestMethod.POST })
    @ResponseBody
    public AjaxJson getDict(@RequestBody Dict dict) {
        AjaxJson json = new AjaxJson();
        List list = new ArrayList();
        switch (dict.getCode()) {
            case "activityCate":
                list = this.cast2List(new EnumInterface[]{
                        ActivityCateEnum.ACTIVITY, ActivityCateEnum.PROMOTION, ActivityCateEnum.COMPETITION
                });
                break;
            case "userRank":
                list = this.cast2List(new EnumInterface[]{
                        UserRankEnum.RANKONE, UserRankEnum.RANKTWO, UserRankEnum.RANKTHREE,
                        UserRankEnum.RANKFOUR, UserRankEnum.RANKFIVE, UserRankEnum.RANKSIX
                });
                break;
            case "radar":
                list = Arrays.asList(new String[]{
                        UserRadarEnum.RADARONE.getMsg(), UserRadarEnum.RADARTWO.getMsg(), UserRadarEnum.RADARTHREE.getMsg(),
                        UserRadarEnum.RADARFOUR.getMsg(), UserRadarEnum.RADARFIVE.getMsg(), UserRadarEnum.RADARSIX.getMsg()
                });
                break;
            case "vipStyle":
                list = this.cast2List(new EnumInterface[]{
                        UserVipStyleEnum.STYLEONE, UserVipStyleEnum.STYLETWO, UserVipStyleEnum.STYLETHREE,
                        UserVipStyleEnum.STYLEFOUR, UserVipStyleEnum.STYLEFIVE, UserVipStyleEnum.STYLESIX,
                        UserVipStyleEnum.STYLESEVEN, UserVipStyleEnum.STYLEEIGHT
                });
                break;
            default:
                break;
        }
        json.setData(list);
        return json;
    }

    /**
     * 把Enum变成列表返回
     * @param enumInfs
     * @return
     */
    private List<Map<String, Object>> cast2List(EnumInterface[] enumInfs) {
        if (enumInfs == null) {
            return null;
        } else {
            List<Map<String, Object>> list = new ArrayList<>(enumInfs.length);
            Map<String, Object> map = null;

            for(EnumInterface enumInterface : enumInfs) {
                map = new HashMap<>();
                map.put("id", enumInterface.getCode());
                map.put("title", enumInterface.getMsg());
                list.add(map);
            }
            return list;
        }
    }

}
